import api from '../../api';
import { apiModeUtils } from '../../apiConfig';
import type { Role } from '../../../types/rbac';

// 角色相关接口类型定义
export interface RoleWithUserCount extends Role {
  userCount: number;
}

export interface RoleListParams {
  page?: number;
  size?: number;
  name?: string;
  code?: string;
  status?: 'active' | 'inactive';
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

export interface CreateRoleRequest {
  name: string;
  code: string;
  description?: string;
  permissions?: string[];
  status?: 'active' | 'disabled'; // 使用StatusEnum的字符串代码
}

export interface UpdateRoleRequest {
  name?: string;
  code?: string;
  description?: string;
  permissions?: string[];
  status?: 'active' | 'disabled'; // 使用StatusEnum的字符串代码
}

export interface RoleListResponse {
  records: RoleWithUserCount[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
  first: boolean;
  last: boolean;
}

export interface AssignPermissionsRequest {
  roleId: string;
  permissions: string[];
}

export interface AssignUsersRequest {
  roleId: string;
  userIds: string[];
}

export interface RolePermission {
  id: string;
  name: string;
  code: string;
  type: 'menu' | 'button' | 'api';
  parentId?: string;
  path?: string;
  method?: string;
  description?: string;
  sort: number;
  children?: RolePermission[];
}

// 创建角色API包装器
const api_role = apiModeUtils.createApi('roleApi', api, false);

// 真实角色管理API服务
const realRoleApi = {
  // 获取角色列表
  getRoles: (params?: RoleListParams): Promise<RoleListResponse> => {
    const requestData = {
      current: params?.page || 1,
      size: params?.size || 10,
      ...params,
    };
    return api_role.post('getRoles', '/system/api/v3/sys/roles/page', requestData);
  },

  // 获取所有角色（不分页）
  getAllRoles: (): Promise<RoleWithUserCount[]> => {
    return api_role.get('getAllRoles', '/system/api/v3/sys/roles/all');
  },

  // 获取角色详情
  getRole: (id: string): Promise<RoleWithUserCount> => {
    return api_role.get('getRole', `/system/api/v3/sys/roles/${id}`);
  },

  // 创建角色
  // 创建角色
  createRole: (data: CreateRoleRequest): Promise<RoleWithUserCount> => {
    // 转换前端数据格式到后端格式
    const requestData = {
      name: data.name,
      code: data.code,
      description: data.description,
      // 使用StatusEnum的字符串代码：'active'对应启用，'disabled'对应禁用
      status: data.status === 'active' ? 'active' : 'disabled',
    };
    return api_role.post('createRole', '/system/api/v3/sys/roles/add', requestData);
  },

  // 更新角色
  updateRole: (id: string, data: UpdateRoleRequest): Promise<RoleWithUserCount> => {
    // 转换前端数据格式到后端格式，必须包含id字段
    const requestData = {
      id: id, // 后端SysRoleDto要求包含id字段
      name: data.name,
      code: data.code,
      description: data.description,
      // 使用StatusEnum的字符串代码：'active'对应启用，'disabled'对应禁用
      status: data.status === 'active' ? 'active' : 'disabled',
    };
    return api_role.put('updateRole', '/system/api/v3/sys/roles/update', requestData);
  },

  // 删除角色
  deleteRole: (id: string): Promise<void> => {
    return api_role.delete('deleteRole', `/system/api/v3/sys/roles/delete/${id}`);
  },

  // 批量删除角色
  batchDeleteRoles: (ids: string[]): Promise<void> => {
    return api_role.delete('batchDeleteRoles', '/system/api/v3/sys/roles/batch', { data: { ids } });
  },

  // 分配权限给角色
  assignPermissions: (data: AssignPermissionsRequest): Promise<void> => {
    // 直接发送权限代码数组，后端会自动判断是权限代码还是权限ID
    console.log('分配权限API调用，角色ID:', data.roleId, '权限代码:', data.permissions);
    return api_role.put('assignPermissions', `/system/api/v3/sys/roles/${data.roleId}/permissions`, data.permissions);
  },

  // 获取角色权限
  getRolePermissions: (id: string): Promise<string[]> => {
    // 后端返回权限代码的Set<String>，前端需要转换为数组
    return api_role.get('getRolePermissions', `/system/api/v3/sys/roles/${id}/permissions`)
      .then(permissionCodes => Array.from(permissionCodes || []));
  },

  // 获取角色权限树
  getRolePermissionTree: (id: string): Promise<RolePermission[]> => {
    return api_role.get('getRolePermissionTree', `/system/api/v3/sys/roles/${id}/permissions/tree`);
  },

  // 分配用户给角色
  assignUsers: (data: AssignUsersRequest): Promise<void> => {
    return api_role.put('assignUsers', `/system/api/v3/sys/roles/${data.roleId}/users`, { 
      userIds: data.userIds 
    });
  },

  // 获取角色下的用户
  getRoleUsers: (id: string, params?: {
    page?: number;
    size?: number;
    username?: string;
  }): Promise<{
    content: any[];
    totalElements: number;
  }> => {
    return api_role.get('getRoleUsers', `/system/api/v3/sys/roles/${id}/users`, { params });
  },

  // 从角色中移除用户
  removeUsersFromRole: (roleId: string, userIds: string[]): Promise<void> => {
    return api_role.delete('removeUsersFromRole', `/system/api/v3/sys/roles/${roleId}/users`, { 
      data: { userIds } 
    });
  },

  // 检查角色代码是否存在
  checkRoleCode: (code: string, excludeId?: string): Promise<{ exists: boolean }> => {
    return api_role.get('checkRoleCode', '/system/api/v3/sys/roles/check-code', { 
      params: { code, excludeId } 
    });
  },

  // 检查角色名称是否存在
  checkRoleName: (name: string, excludeId?: string): Promise<{ exists: boolean }> => {
    return api_role.get('checkRoleName', '/system/api/v3/sys/roles/check-name', { 
      params: { name, excludeId } 
    });
  },

  // 启用/禁用角色
  // 切换角色状态
  toggleRoleStatus: (id: string, status: 'active' | 'disabled'): Promise<void> => {
    const endpoint = status === 'active' ? 'enable' : 'disable';
    return api_role.put('toggleRoleStatus', `/system/api/v3/sys/roles/${id}/${endpoint}`);
  },

  // 复制角色
  copyRole: (id: string, newName: string, newCode: string): Promise<RoleWithUserCount> => {
    return api_role.post('copyRole', `/system/api/v3/sys/roles/${id}/copy`, { 
      name: newName, 
      code: newCode 
    });
  },

  // 获取角色统计信息
  getRoleStats: (): Promise<{
    totalRoles: number;
    activeRoles: number;
    inactiveRoles: number;
    rolesWithUsers: number;
  }> => {
    return api_role.get('getRoleStats', '/system/api/v3/sys/roles/stats');
  },

  // 导出角色数据
  exportRoles: (params?: RoleListParams): Promise<Blob> => {
    return api_role.get('exportRoles', '/system/api/v3/sys/roles/export', { 
      params,
      responseType: 'blob'
    });
  },

  // 获取角色权限对比
  compareRolePermissions: (roleIds: string[]): Promise<{
    roles: Role[];
    permissions: {
      id: string;
      name: string;
      code: string;
      rolePermissions: { [roleId: string]: boolean };
    }[];
  }> => {
    return api_role.post('compareRolePermissions', '/system/api/v3/sys/roles/compare-permissions', { roleIds });
  },

  // 批量设置角色权限
  batchSetPermissions: (data: {
    roleIds: string[];
    permissions: string[];
    action: 'add' | 'remove' | 'replace';
  }): Promise<void> => {
    return api_role.post('batchSetPermissions', '/system/api/v3/sys/roles/batch-permissions', data);
  },

  // 为角色分配菜单权限
  assignMenusToRole: (roleId: string, menuIds: string[]): Promise<void> => {
    // 将菜单ID字符串数组转换为Long数组，与后端API期望的格式保持一致
    const menuIdNumbers = menuIds
      .map(id => parseInt(id, 10))
      .filter(id => !isNaN(id));
    
    console.log('分配菜单权限API调用，角色ID:', roleId, '菜单IDs:', menuIdNumbers);
    return api_role.post('assignMenusToRole', `/system/api/v3/sys/roles/${roleId}/menus`, menuIdNumbers);
  },

  // 获取角色菜单权限
  getRoleMenus: (roleId: string): Promise<string[]> => {
    // 后端返回菜单ID的List<Long>，前端需要转换为字符串数组
    return api_role.get('getRoleMenus', `/system/api/v3/sys/roles/${roleId}/menus`)
      .then(menuIds => (menuIds || []).map((id: number) => String(id)));
  },
};

/**
 * 角色管理API服务 - 仅使用真实后端接口
 */
export const roleApi = realRoleApi;